﻿
using Aspose.Cells.Rendering;
using HualongExcel.Enum;
using HualongExcel.Utilities;
using Microsoft.Office.Tools;
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Workbook = Aspose.Cells.Workbook;
using Worksheet = Aspose.Cells.Worksheet;

namespace HualongExcel
{
    public partial class TablePreviewWindow : UserControl
    {

        private static CustomTaskPane Task_TablePreviewWindow;

        //string previewFilePath;
        //创建一个纸张底色渲染对象
        SheetRender sheetRender=null;
        Worksheet sheet;
        ImageOrPrintOptions imgOptions;

        int currentPage=0;


        #region 表格预览窗口方法
        /// <summary>
        /// 打开表格预览窗口
        /// </summary>
        public static void OpenTablePreviewWindow()
        {


            if (Task_TablePreviewWindow == null)
            {
                TablePreviewWindow previewWindow = new TablePreviewWindow();
                Task_TablePreviewWindow = Globals.HualongExcel.CustomTaskPanes.Add(previewWindow, "表格预览");
                Task_TablePreviewWindow.VisibleChanged += OnPreviewWinodwVisibleChangeEventHandler;
                Task_TablePreviewWindow.Width = 300;
                Task_TablePreviewWindow.Visible = true;
            }
            else
            {
                if (!Task_TablePreviewWindow.Visible)
                {
                    Task_TablePreviewWindow.Visible = true;
                }
            }

        }

        /// <summary>
        /// 当预览窗体可见性改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnPreviewWinodwVisibleChangeEventHandler(object sender, EventArgs e)
        {
            if (Task_TablePreviewWindow.Visible)
            {
                Task_TablePreviewWindow.Control.Show();
            }
            else
            {
                Task_TablePreviewWindow.Control.Hide();
            }
        }

        /// <summary>
        /// 关闭表格预览窗口
        /// </summary>
        public static void CloseTablePreviewWindow()
        {
            Globals.HualongExcel.CustomTaskPanes.Remove(Task_TablePreviewWindow);
            Task_TablePreviewWindow = null;
        }

        #endregion

        public TablePreviewWindow()
        {
            InitializeComponent();
        }

        private void TablePreviewWindow_Load(object sender, EventArgs e)
        {
            Workbook book = new Workbook(Common.WorktemplateData.templatePath);
            //创建一个图表选项的对象
            imgOptions = new ImageOrPrintOptions();
            //设置图片类型
            imgOptions.ImageType = Aspose.Cells.Drawing.ImageType.Png;
            //获取第一张工作表
            sheet = book.Worksheets[0];
            RefreshPageButton();
        }

        protected virtual void OnShow()
        {
            Common.CurrentExcelApp.SheetSelectionChange += OnSheetSelectionChangedHandler;

            ReGenerateTableInMultiThread();
        }

        protected virtual void OnHide()
        {
            Common.CurrentExcelApp.SheetSelectionChange -= OnSheetSelectionChangedHandler;
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (this.Visible)
            {
                OnShow();
            }
            else
            {
                OnHide();
            }
        }


        private void OnSheetSelectionChangedHandler(object Sh, Microsoft.Office.Interop.Excel.Range Target)
        {
            ReGenerateTableInMultiThread();
        }



        private void ReGenerateTableInMultiThread()
        {
            ThreadStart generateTheradStarter = new ThreadStart(ReGenerateTable);
            Thread generateThread = new Thread(generateTheradStarter);
            generateThread.Start();

        }

        /// <summary>
        /// 重新生成表格
        /// </summary>
        private void ReGenerateTable()
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            foreach (var pair in Common.WorktemplateData.mapping)
            {


                var targetAddress = pair.Value.Replace("$", String.Empty);


                var pattern = @"\{(.*?)\}";
                var match = Regex.Match(pair.Key, pattern);//匹配{}
                if (match.Success)//如果匹配成功，则说明映射的是变量
                {
                    sheet.Cells[targetAddress].PutValue(pair.Key.ReplaceVariable());
                    continue;
                }

                string source_address = pair.Key;


                var ColumnStartIndex = source_address.IndexOf("$");
                var RowStartIndex = source_address.LastIndexOf("$");


                var Column_Address = source_address.Substring(ColumnStartIndex + 1, RowStartIndex - 1);
                var Row_Address = source_address.Substring(RowStartIndex + 1);


               

                //c = Column_Address.ToIndex();
                //r = int.Parse(Row_Address);


                switch (Common.SelectedReplaceType)
                {
                    case ReplaceType.WithRow://跟随当前行
                        Row_Address = Common.SelectedRow.ToString();
                        break;
                    case ReplaceType.WithColumn://跟随当前列
                        Column_Address = Common.SelectedColumn.ToName();
                        break;
                }


      
                source_address = $"{Column_Address}{Row_Address}";
                string contentValue =Convert.ToString(Common.CurrentExcelApp.Range[source_address].Value);

                sheet.Cells[targetAddress].PutValue(contentValue.ReplaceVariable());//映射的值为当前单元格内容替
            }
           
            sheetRender = new SheetRender(sheet, imgOptions);
            //sw.Stop();
            //TimeSpan ts = sw.Elapsed;
            //MessageBox.Show($"算法耗时：{ts.TotalMilliseconds}ms");

            RefreshPreview();
        }

        private void RefreshPreview()
        {
            if(sheetRender!=null)
                PreviewPictureBox.Image = sheetRender.ToImage(currentPage);
        }


        /// <summary>
        ///  当窗体大小修改时
        /// </summary>
        /// <param name="e"></param>

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            PreviewPictureBox.Width = this.Width;
            PreviewPictureBox.Height = this.Height;

            nextPageButton.Width = this.Width /9;
            previousPageButton.Width = nextPageButton.Width;

            nextPageButton.Height = this.Height / 18;
            previousPageButton.Height = nextPageButton.Height;

            nextPageButton.Left = this.Width - nextPageButton.Width;
            nextPageButton.Top = this.Height - nextPageButton.Height;

            previousPageButton.Left = 0;
            previousPageButton.Top = this.Height - previousPageButton.Height;

            RefreshPageButton();


        }

        private void nextPageButton_Click(object sender, EventArgs e)
        {
            if (currentPage < sheetRender.PageCount - 1)
                currentPage++;
            ReGenerateTableInMultiThread();
            RefreshPageButton();
        }

        private void previousPageButton_Click(object sender, EventArgs e)
        {
            if (currentPage > 0)
                currentPage--;
            ReGenerateTableInMultiThread();
            RefreshPageButton();
        }

        private void RefreshPageButton()
        {
            if (sheetRender != null)
            {
                nextPageButton.Visible = (currentPage < sheetRender.PageCount - 1) && sheetRender.PageCount > 1;
                previousPageButton.Visible = (currentPage > 0) && sheetRender.PageCount > 1;
            }
            else
            {
                nextPageButton.Visible = false;
                previousPageButton.Visible = false;
            }
        }
    }
}
